//
//  MJTabBar.m
//  NewClothesForEveryDay
//
//  Created by dllo on 15/7/13.
//  Copyright (c) 2015年 蓝天. All rights reserved.
//

#import "MJTabBar.h"
#import "MJTabBarButton.h"



@interface MJTabBar()

@property (nonatomic, retain) UIButton *selectButton;

@end



@implementation MJTabBar

/**
 *  内存管理
 */
- (void)dealloc
{
    [_selectButton release];
    [super dealloc];
}

- (void)addTabBarButtonWithName:(NSString *)name selName:(NSString *)selName
{
    MJTabBarButton *button = [MJTabBarButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:selName] forState:UIControlStateSelected];
    [self addSubview:button];
    // 监听
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    // 默认选中界面
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}

- (void)buttonClick:(UIButton *)button
{
    // 判断TabBarController 是否有某种方法 respondsToselector:(SEL)
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectItemFrom:to:)]) {
        [self.delegate tabBar:self didSelectItemFrom:self.selectButton.tag to:button.tag];
    }
    // 当前按钮取消选中
    self.selectButton.selected = NO;
    // 新点击的按钮选中
    button.selected = YES;
    // 新点击的按钮成为"当前选中的按钮"
    self.selectButton = button;
}
/**
 *  重写布局方法
 */

- (void)layoutSubviews
{
    [super layoutSubviews];
    NSInteger count = self.subviews.count;
    for (int i = 0 ; i < count ; i++) {
        MJTabBarButton *button = self.subviews[i];
        button.tag = i;
        // 设置frame
        CGFloat buttonY = 0;
        CGFloat buttonW = self.frame.size.width / count;
        CGFloat buttonH = self.frame.size.height;
        CGFloat buttonX = i * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
    }
}


@end
